# app/controllers/user_controller.py

from flask import Blueprint,request,Flask
from utils.response_utils import ResponseUtils
from service.user_service import UserService
from application.user_application import UserApplication
from service.oss_service import OssService

user = Blueprint('user', __name__)

@user.route('/get_user_by_user_id', methods=['POST'])
def get_user_by_user_id():
    try:
        user_id = request.get_json().get("user_id")
        res = UserService.get_user_by_user_id(user_id)
        return ResponseUtils.success(res,code=200)
    except Exception as e:
        return ResponseUtils.error(message=str(e), code=500)
    
@user.route('/update_user_avatar', methods=['POST'])
def update_user_avatar():
    try:
        user_id = request.form['user_id']
        file = request.files['file']
        avatar_urls = OssService.aliyun_upload_file(file)
        print(avatar_urls)
        avatar_url = avatar_urls['file_url']
        res = UserService.update_user_avatar(avatar_url,user_id)
        return ResponseUtils.success(data={"avatar_url": avatar_url})
    except Exception as e:
        return ResponseUtils.error(message=str(e), code=500)

    
@user.route('/update_user_pass', methods=['POST'])
def update_user_pass():
    try:
        user_name = request.get_json().get('user_name')
        password = request.get_json().get('password')
        new_password = request.get_json().get('new_password')
        user_id = request.get_json().get('user_id')
        res = UserApplication.update_user_pass(password,user_name,user_id,new_password)
        return ResponseUtils.success(res)
    except Exception as e:
        return ResponseUtils.error(message=str(e), code=500)

@user.route('/register_user', methods=['POST'])
def register_user():
    try:
        user_name = request.get_json().get('user_name')
        password = request.get_json().get('password')
        user_id = request.get_json().get('user_id')
        res = UserApplication.register_user(password,user_name,user_id)
        return ResponseUtils.success(data=res)
    except Exception as e:
        return ResponseUtils.error(message=str(e), code=500)

@user.route('/login', methods=['POST'])
def login():
    try:
        print('login',request)
        user_name = request.get_json().get('user_name')
        password = request.get_json().get('password')
        res = UserApplication.login(password,user_name)
        return ResponseUtils.success(data=res)
    except Exception as e:
        return ResponseUtils.error(message=str(e), code=500)